﻿using System;
using System.ServiceModel;
using ServiceProxy;

namespace CalculatorTwo
{
    /// <summary>
    /// Implementation of a calculator which provides simple arithmetic operations
    /// </summary>
    public class Calculator
    {
        /* Prefered mocking framework Moq only supports mocking interface or virtual method
         * The CalculatorClient does not contain virtual methods so mocking is not possible
         * Use ChannelFactory to instantiate client with use of generated channel interface
         * Channel is now injected by constructor injection (to keep things simple for this demo)
         * Problem is that the caller is now responsible for the creation of the channel
         * 
         * There is also still a lot of exception handling code */

        private readonly ICalculatorChannel calculatorClient;

        public Calculator(ICalculatorChannel calculatorClient)
        {
            this.calculatorClient = calculatorClient;
        }

        /// <summary>
        /// Adds two numbers and returns the result
        /// </summary>
        /// <param name="numberOne"></param>
        /// <param name="numberTwo"></param>
        /// <returns></returns>
        public float Add(float numberOne, float numberTwo)
        {
            float response = 0f;

            //Do not use the using statement when working with a WCF client: http://msdn.microsoft.com/en-us/library/aa355056.aspx)
            try
            {
                response = calculatorClient.add(numberOne, numberTwo);
                calculatorClient.Close();
            }
            catch (CommunicationException)
            {
                calculatorClient.Abort();
            }
            catch (TimeoutException)
            {
                calculatorClient.Abort();
            }
            catch (Exception)
            {
                calculatorClient.Abort();
                throw;
            }

            return response;
        }
    }
}